<?php

/**
 * This is the model class for table "dat_gallerie".
 *
 * The followings are the available columns in table 'dat_gallerie':
 * @property integer $id
 * @property string $title
 * @property string $description
 * @property string $Path
 * @property integer $idAutore
 *
 * The followings are the available model relations:
 * @property Autori $idAutore0
 * @property DatImmagini[] $datImmaginis
 * @property DatLetteratura[] $datLetteraturas
 * @property DatMusica[] $datMusicas
 * @property DatVideo[] $datVideos
 */
class Galleria extends CActiveRecord {

    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return Galleria the static model class
     */
    public static function model($className=__CLASS__) {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName() {
        return 'dat_gallerie';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules() {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('idAutore', 'numerical', 'integerOnly' => true),
            array('title, Path', 'length', 'max' => 500),
            array('description', 'length', 'max' => 1500),
            array('idTipoGalleria', 'numerical', 'integerOnly' => true),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('id, title, description, Path, idAutore', 'safe', 'on' => 'search'),
            array('title', 'required'),
            array('Path', 'required'),
            array('idTipoGalleria', 'required'),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations() {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
            'Autore' => array(self::BELONGS_TO, 'Autore', 'idAutore'),
            'Immagini' => array(self::HAS_MANY, 'Immagine', 'idGalleria'),
            'Letteratura' => array(self::HAS_MANY, 'Letteratura', 'idGalleria'),
            'Musica' => array(self::HAS_MANY, 'Musica', 'idGalleria'),
            'Video' => array(self::HAS_MANY, 'Video', 'idGalleria'),
            'Tipo' => array(self::BELONGS_TO, 'TipoGalleria', 'idTipoGalleria')
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
        return array(
            'id' => 'ID',
            'title' => 'Titolo',
            'description' => 'Descrizione',
            'Path' => 'Percorso files',
            'idAutore' => 'Autore',
            'idTipoGalleria' => 'Tipo',
        );
    }
    
    public function saveGal($fileEntries=null) {
        if (!$this->save())
            return false;
        $destination = $this->getFullPath();
        if (!is_dir($destination))
            mkdir($destination);
        
        if($this->Tipo->cod == 'I')
        {
            if (isset($fileEntries) && count($fileEntries) > 0) {
                foreach ($fileEntries as $image => $pic) {
                    if ($pic->saveAs($destination . "/" . $pic->name)) {
                        $image = new Immagine();
                        $image->title = $pic->name;
                        $image->idGalleria = $this->id;
                        $image->files = new FileInfos();
                        $image->files->FilesName = $destination . "/" . $pic->name;
                        $image->files->Thumbnails = $destination . "/thumb_" . $pic->name;
                        $image->files->createThumb($image->files->Thumbnails, $image->files->FilesName, Yii::app()->params['widthThumb']);
                        $image->files->save();
                        $image->FilesID = $image->files->FilesID;
                        $image->save();
                    }
                }
            }
        }
        if($this->Tipo->cod == 'V')
        {
            if (isset($fileEntries) && count($fileEntries) > 0) {
                foreach ($fileEntries as $item => $video)
                {
                    if ($video->saveAs($destination . "/" . $video->name)) {
                        $videoItem = new Video();
                        $videoItem->title = $video->name;
                        $videoItem->descr = "";
                        $videoItem->idGalleria = $this->id;
                        $videoItem->files = new FileInfos();
                        $videoItem->files->FilesName = $destination . "/" . $pic->name;
                        $videoItem->files->save();
                        $videoItem->FilesID = $videoItem->files->FilesID;
                        $videoItem->save();
                    }
                }
            }
        }
        if($this->Tipo->cod == 'M')
        {
            if (isset($fileEntries) && count($fileEntries) > 0) {
                foreach ($fileEntries as $item => $music)
                {
                    if ($music->saveAs($destination . "/" . $music->name)) {
                        $musicItem = new Musica();
                        $musicItem->title = $music->name;
                        $videoItem->descr = "";
                        $videoItem->idGalleria = $this->id;
                        $videoItem->files = new FileInfos();
                        $videoItem->files->FilesName = $destination . "/" . $pic->name;
                        $videoItem->files->save();
                        $videoItem->FilesID = $videoItem->files->FilesID;
                        $videoItem->save();
                    }
                }
            }
        }
        return true;
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function getFullPath() {
        $imageFolder = Yii::app()->params['imageFolder'];
        if (!isset($imageFolder))
            throw new CHttpException(400, 'Image Folder is no set');
        if (!isset($this->idAutore))
            throw new CHttpException(400, 'ID Autore is not set');
        $author = Autore::model()->findByPk($this->idAutore);
        if (!isset($author))
            throw new CHttpException(400, 'Non esiste nessun autore associato a quell\' ID');

        return $imageFolder . $author->nome . "/" . $this->Path;
    }

    public function search() {
        // Warning: Please modify the following code to remove attributes that
        // should not be searched.

        $criteria = new CDbCriteria;

        $criteria->compare('id', $this->id);
        $criteria->compare('title', $this->title, true);
        $criteria->compare('description', $this->description, true);
        $criteria->compare('Path', $this->Path, true);
        $criteria->compare('idAutore', $this->idAutore);

        return new CActiveDataProvider($this, array(
                    'criteria' => $criteria,
                ));
    }

    public function searchByIdAutore($idAutore) {
        $criteria = new CDbCriteria;
        $criteria->compare('idAutore', $idAutore);
        return new CActiveDataProvider($this, array(
                    'criteria' => $criteria,
                ));
    }

    
    public function deleteCascade() {
        foreach ($this->Immagini as $immagine)
            $immagine->deleteCascade();
        foreach ($this->Letteratura as $letteratura)
            $letteratura->deleteByPk($letteratura->id);
        foreach ($this->Musica as $musica)
            $musica->deleteCascade();
        foreach ($this->Video as $video)
            $video->deleteCascade();

        //$pathname = 'images/galleries/';
        //$destination = $pathname . $this->Autore->nome . "/" . $this->title;
        $path = $this->getFullPath();
        if (is_dir($path))
            Yii::app()->fileManager->emptyDir($path,true);
        $this->deleteByPk($this->id);
    }

}